<template>
  <div class="page">
    <div class="header-num">
      <div><span class="page-num">2</span><span class="page-title">申请人员信息</span></div>
      <div class="plan">2/5</div>
    </div>
    <div class="info-message">
      <div class="info-title">代办人信息</div>
      <div class="info-form">
        <van-form ref="dataForm" label-width="30%" @submit="onSubmit">
          <van-cell-group inset>
            <van-field v-model="proxyName" label="姓名" placeholder="姓名" required :rules="dataRule.proxyName" />
            <van-field v-model="proxyPhone" type="tel" label="联系电话" placeholder="联系电话" maxlength="11" required :rules="dataRule.proxyPhone" />
            <van-field v-model="proxyDeptCode" label="所属部门" placeholder="所属部门" required :rules="dataRule.proxyDeptCode" />
          </van-cell-group>
        </van-form>
      </div>
    </div>
    <div class="info-message">
      <div class="info-title">申请人信息</div>
      <div class="info-form">
        <van-form ref="dataForm" label-width="30%" @submit="onSubmit">
          <van-cell-group inset>
            <van-field v-model="applyName" label="姓名" placeholder="姓名" required :rules="dataRule.applyName" />
            <van-field
              readonly
              v-model="applySex"
              is-link
              required
              name="picker"
              label="性别"
              placeholder="点击选择性别"
              :rules="dataRule.applySex"
              @click="showPicker = true"
            />
            <van-popup v-model:show="showPicker" position="bottom">
              <van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
            </van-popup>
            <van-field v-model="applyAge" type="digit" label="年龄" placeholder="年龄" required :rules="dataRule.applyAge" />
            <van-field v-model="applyPhone" type="tel" label="联系电话" placeholder="联系电话" maxlength="11" required :rules="dataRule.applyPhone" />
            <van-field v-model="applyIdcard" label="身份证号" placeholder="身份证号" maxlength="18" required :rules="dataRule.applyIdcard" />
            <custom-select
              :selectId="applyCountry"
              :columns="areaList"
              :option="{ label: 'regionName', value: 'regionCode' }"
              :rules="dataRule.applyCountry"
              required
              label="户口所在地"
              placeholder="点击选择户口所在地"
              label-width="30%"
              @getValue="getValue"
            ></custom-select>
            <van-field
              v-model="applyFamilySize"
              type="digit"
              label="家庭人口数"
              placeholder="家庭人口数"
              required
              :rules="dataRule.applyFamilySize"
            />
            <van-field v-model="applyHouseAddress" label="家庭住址" placeholder="家庭住址" required :rules="dataRule.applyHouseAddress" />
          </van-cell-group>
        </van-form>
      </div>
    </div>
    <div class="info-message">
      <div class="info-header">
        <div class="left">家庭成员信息</div>
        <div class="right" @click="handleToEdit(0, 'add')">新增</div>
      </div>
      <div class="info-user">
        <van-cell v-for="item in familyMemberList" :key="item.id" is-link :title="item.name" @click="handleToEdit(item.id, 'edit')" />
      </div>
    </div>
    <div class="btn-group">
      <van-button type="button" class="cus-btn btn-default" @click="goBack">上一步</van-button>
      <van-button :loading="isCommit" type="button" class="cus-btn btn-default" @click="onSubmit">保存</van-button>
      <van-button type="button" class="cus-btn btn-primary" @click="goNext">下一步</van-button>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs, computed,getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { Toast } from 'vant'
import $localStorage from '@/utils/localStorage.js'
import { saveBuildApply } from '@/service/build-apply'
export default {
  setup() {
    // 全局属性
    const { $verify } = getCurrentInstance().appContext.config.globalProperties
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const showPicker = ref(false)
    const dataForm = ref(null)
    const columns = ['男', '女']
    const state = reactive({
      isCommit: false,
      proxyName: '',
      proxyPhone: '',
      proxyDeptCode: '',
      id: '',
      applyName: '',
      applySex: '',
      applyAge: '',
      applyPhone: '',
      applyIdcard: '',
      applyHouseAddress: '',
      applyFamilySize: '',
      applyProvince: '',
      applyCity: '',
      applyCountry: null,
      applyUserInfo: {},
      familyMemberList: [],
      dataRule: {
        proxyName: [{ required: true, message: '请输入代办人姓名', trigger: 'onBlur' }],
        proxyPhone: [{ required: true, message: '请输入代办人联系电话', trigger: 'onBlur', validator: $verify.validatorPhone }],
        proxyDeptCode: [{ required: true, message: '请输入代办人所属部门', trigger: 'onBlur' }],
        applyName: [{ required: true, message: '请输入申请人姓名', trigger: 'onBlur' }],
        applySex: [{ required: true, message: '请选择申请人性别', trigger: 'onChange' }],
        applyAge: [{ required: true, message: '请输入申请人年龄', trigger: 'onBlur' }],
        applyPhone: [{ required: true, message: '请输入申请人联系电话', trigger: 'onBlur', validator: $verify.validatorPhone }],
        applyIdcard: [{ required: true, message: '请输入申请人身份证号', trigger: 'onBlur', validator: $verify.validatorIDcard }],
        applyCountry: [{ required: true, message: '请选择申请人户口所在地', trigger: 'onChange' }],
        applyFamilySize: [{ required: true, message: '请输入申请人家庭人口数', trigger: 'onBlur' }],
        applyHouseAddress: [{ required: true, message: '请输入申请人家庭住址', trigger: 'onBlur' }],
      },
    })
    const showArea = ref(false)

    // 获取字典数据
    store.dispatch('getTownOptions')

    onMounted(() => {
      init()
    })

    const init = async () => {
      state.applyUserInfo = JSON.parse($localStorage.get('applyUserInfo_govern'))
      state.familyMemberList = JSON.parse($localStorage.get('familyMemberList_govern')) || []
      if (state.applyUserInfo && Object.keys(state.applyUserInfo).length > 0) {
        state.proxyName = state.applyUserInfo.proxyName
        state.proxyPhone = state.applyUserInfo.proxyPhone
        state.proxyDeptCode = state.applyUserInfo.proxyDeptCode
        state.id = state.applyUserInfo.id
        state.applyName = state.applyUserInfo.applyName
        state.applySex = state.applyUserInfo.applySex == 1 ? '男' : state.applyUserInfo.applySex == 2 ? '女' : state.applyUserInfo.applySex
        state.applyAge = state.applyUserInfo.applyAge
        state.applyPhone = state.applyUserInfo.applyPhone
        state.applyIdcard = state.applyUserInfo.applyIdcard
        state.applyHouseAddress = state.applyUserInfo.applyHouseAddress
        state.applyFamilySize = state.applyUserInfo.applyFamilySize
        state.applyCity = state.applyUserInfo.applyCity
        state.applyProvince = state.applyUserInfo.applyProvince
        state.applyCountry = Number(state.applyUserInfo.applyCountry)
      }
    }
    // 性别选择
    const onConfirm = (value) => {
      state.applySex = value
      showPicker.value = false
    }
    // 获取户口所在地id
    const getValue = (val) => {
      state.applyCountry = Number(val)
    }
    const onSubmit = () => {
      saveLocal()
      const applyUserInfo = JSON.parse($localStorage.get('applyUserInfo_govern'))
      const familyMemberList = JSON.parse($localStorage.get('familyMemberList_govern'))
      let params = Object.assign({ isSubmit: '0', familyMemberList: familyMemberList }, applyUserInfo)
      state.isCommit = true
      saveBuildApply(params)
        .then((res) => {
          if (res.code == 100) {
            Toast.success('保存成功')
            setTimeout(() => {
              router.push({ path: '/government/record-apply/record-list' })
            }, 500)
          }
          state.isCommit = false
        })
        .catch(() => {
          state.isCommit = false
        })
    }
    const goBack = () => {
      saveLocal()
      router.push({ path: '/government/build-apply/apply-notes', query: { id: route.query.id } })
    }
    const goNext = () => {
      if (state.familyMemberList.length === 0) {
        Toast.fail(`请添加家庭成员信息`)
        return
      }
      dataForm.value.validate().then(() => {
        saveLocal()
        router.push({
          path: '/government/build-apply/apply-base',
        })
      })
    }
    const saveLocal = () => {
      state.applyUserInfo = {}
      state.applyUserInfo.proxyName = state.proxyName
      state.applyUserInfo.proxyPhone = state.proxyPhone
      state.applyUserInfo.proxyDeptCode = state.proxyDeptCode
      state.applyUserInfo.id = state.id
      state.applyUserInfo.applyName = state.applyName
      state.applyUserInfo.applySex = state.applySex === '男' ? '1' : state.applySex === '女' ? '2' : state.applySex
      state.applyUserInfo.applyAge = state.applyAge
      state.applyUserInfo.applyPhone = state.applyPhone
      state.applyUserInfo.applyIdcard = state.applyIdcard
      state.applyUserInfo.applyHouseAddress = state.applyHouseAddress
      state.applyUserInfo.applyFamilySize = state.applyFamilySize
      state.applyUserInfo.applyCity = state.applyCity
      state.applyUserInfo.applyProvince = state.applyProvince
      state.applyUserInfo.applyCountry = state.applyCountry
      $localStorage.set('applyUserInfo_govern', JSON.stringify(state.applyUserInfo))
    }

    const handleToEdit = (id, type) => {
      state.applyUserInfo = {}
      state.applyUserInfo.proxyName = state.proxyName
      state.applyUserInfo.proxyPhone = state.proxyPhone
      state.applyUserInfo.proxyDeptCode = state.proxyDeptCode
      state.applyUserInfo.id = state.id
      state.applyUserInfo.applyName = state.applyName
      state.applyUserInfo.applySex = state.applySex === '男' ? '1' : state.applySex === '女' ? '2' : state.applySex
      state.applyUserInfo.applyAge = state.applyAge
      state.applyUserInfo.applyPhone = state.applyPhone
      state.applyUserInfo.applyIdcard = state.applyIdcard
      state.applyUserInfo.applyHouseAddress = state.applyHouseAddress
      state.applyUserInfo.applyFamilySize = state.applyFamilySize
      state.applyUserInfo.applyCity = state.applyCity
      state.applyUserInfo.applyProvince = state.applyProvince
      state.applyUserInfo.applyCountry = state.applyCountry
      $localStorage.set('applyUserInfo_govern', JSON.stringify(state.applyUserInfo))
      router.push({
        path: `/government/build-apply/edit-info`,
        query: { id: id, type: type },
      })
    }

    const areaList = computed(() => {
      return store.state.townOptions
    })

    return {
      showPicker,
      columns,
      showArea,
      dataForm,
      areaList,
      ...toRefs(state),
      goNext,
      onConfirm,
      onSubmit,
      handleToEdit,
      goBack,
      getValue,
    }
  },
}
</script>

<style lang="less" scpoed>
@import '@/common/style/mixin';
.page {
  .btn-group {
    padding-bottom: 20px;
  }
}
.info-message {
  background: #ffffff;
  border-radius: 15px;
  margin-bottom: 20px;
  .info-title {
    padding: 15px;
    font-size: 16px;
    font-weight: bold;
    color: #2e3f6a;
    border-bottom: 1px solid #dee1eb;
  }
  .info-form {
    padding-bottom: 10px;
  }
  .info-header {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #dee1eb;
    .left {
      font-size: 16px;
      font-weight: bold;
      color: #2e3f6a;
    }
    .right {
      font-size: 16px;
      font-weight: 400;
      color: #3487f6;
    }
  }
  .info-user {
    padding-bottom: 20px;
  }
}
</style>